package edu.imu.question.service.impl;

import edu.imu.question.dto.TemplateQuestionDTO;
import edu.imu.question.entity.TemplateQuestion;
import edu.imu.question.entity.TemplateQuestionOption;
import edu.imu.question.mapper.TemplateQuestionMapper;
import edu.imu.question.mapper.TemplateQuestionOptionMapper;
import edu.imu.question.service.TemplateQuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Slf4j
@Service
public class TemplateQuestionServiceImpl implements TemplateQuestionService {
    private TemplateQuestionMapper questionMapper;
    private TemplateQuestionOptionMapper questionOptionMapper;

    @Autowired
    public TemplateQuestionServiceImpl(TemplateQuestionMapper questionMapper, TemplateQuestionOptionMapper questionOptionMapper) {
        this.questionMapper = questionMapper;
        this.questionOptionMapper = questionOptionMapper;
    }

    @Override
    public List<TemplateQuestionDTO> getDetailByTemplate(long templateId) {
        List<TemplateQuestionDTO> list = null;
        List<TemplateQuestion> questions = getByTemplateId(templateId);
        if(questions !=null){
            list = new ArrayList<>();
            for(TemplateQuestion q:questions){
                TemplateQuestionDTO questionDTO = new TemplateQuestionDTO();
                questionDTO.setId(q.getId());
                questionDTO.setTemplateId(templateId);
                questionDTO.setQuestionOrder(q.getQuestionOrder());
                questionDTO.setQuestionNum(q.getQuestionNum());
                questionDTO.setQuestionTitle(q.getQuestionTitle());
                questionDTO.setQuestionType(q.getQuestionType());
                questionDTO.setInputPlaceholder(q.getInputPlaceholder());
                List<TemplateQuestionOption> questionOptions = questionOptionMapper.getByQuestionId(q.getId());
                questionOptions.sort(Comparator.comparing(TemplateQuestionOption::getOptionOrder)); //按照“问题选项”顺序排序
                questionDTO.setQuestionOptions(questionOptions);
                list.add(questionDTO);
            }
            list.sort(Comparator.comparing(TemplateQuestionDTO::getQuestionOrder)); //按照“问题顺序”排序
        }
        return list;
    }

    public List<TemplateQuestion> getByTemplateId(long templateId){
        return questionMapper.getByTemplateId(templateId);
    }
}
